package com.xuecheng.learning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.base.execption.XueChengPlusException;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.model.po.CoursePublish;
import com.xuecheng.learning.feignclient.ContentServiceClient;
import com.xuecheng.learning.mapper.XcChooseCourseMapper;
import com.xuecheng.learning.mapper.XcCourseTablesMapper;
import com.xuecheng.learning.model.dto.MyCourseTableParams;
import com.xuecheng.learning.model.dto.XcChooseCourseDto;
import com.xuecheng.learning.model.dto.XcCourseTablesDto;
import com.xuecheng.learning.model.po.XcChooseCourse;
import com.xuecheng.learning.model.po.XcCourseTables;
import com.xuecheng.learning.service.MyCourseTablesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author Mr.M
 * @version 1.0
 * @description TODO
 * @date 2022/10/2 16:12
 */
@Slf4j
@Service
public class MyCourseTablesServiceImpl implements MyCourseTablesService {

    @Autowired
    XcChooseCourseMapper xcChooseCourseMapper;

    @Autowired
    XcCourseTablesMapper xcCourseTablesMapper;

    @Autowired
    ContentServiceClient contentServiceClient;

    @Autowired
    XcCourseTablesMapper courseTablesMapper;


    /**
     * @description 添加选课
     * @param userId 用户id
     * @param courseId 课程id
     * @return com.xuecheng.learning.model.dto.XcChooseCourseDto
     * @author Mr.M
     * @date 2022/10/24 17:33
     */
    @Transactional
    @Override
    public XcChooseCourseDto addChooseCourse(String userId, Long courseId) {

        //1.选课调用内容管理查询课程的收费规则
        CoursePublish coursepublish = contentServiceClient.getCoursepublish(courseId);
        //课程不为空
        if (coursepublish == null){
            XueChengPlusException.cast("课程不存在！");
        }
        //收费规则
        String charge = coursepublish.getCharge();

        //2.如果免费课程，会向选课记录表、我的课程表写数据
        XcChooseCourse chooseCourse = null;
        if (charge.equals("201000")){
            //添加免费课程
            chooseCourse = addFreeCoruse(userId, coursepublish);
            //添加到我的课程表
            XcCourseTables xcCourseTables = addCourseTabls(chooseCourse);
        }else {
       //3.如果收费课程，会向选课记录表写数据
            chooseCourse = addChargeCoruse(userId, coursepublish);
        }

        //4.判断学生的学习资格
        //创建返回对象
        XcChooseCourseDto xcChooseCourseDto = new XcChooseCourseDto();
        //设置返回参数
        xcChooseCourseDto.setId(chooseCourse.getId());//id
        xcChooseCourseDto.setCourseId(chooseCourse.getCourseId());//课程id
        xcChooseCourseDto.setCourseName(chooseCourse.getCourseName());//课程名称
        xcChooseCourseDto.setUserId(chooseCourse.getUserId());//用户id
        xcChooseCourseDto.setCompanyId(chooseCourse.getCompanyId());//机构id
        xcChooseCourseDto.setOrderType(chooseCourse.getOrderType());//选课类型
        xcChooseCourseDto.setCreateDate(chooseCourse.getCreateDate());//创建时间
        xcChooseCourseDto.setValidDays(chooseCourse.getValidDays());//有效时间
        xcChooseCourseDto.setCoursePrice(chooseCourse.getCoursePrice());//价格
        xcChooseCourseDto.setStatus(chooseCourse.getStatus());//状态
        xcChooseCourseDto.setValidtimeStart(chooseCourse.getValidtimeStart());//开始时间
        xcChooseCourseDto.setValidtimeEnd(chooseCourse.getValidtimeEnd());//结束时间
        xcChooseCourseDto.setRemarks(chooseCourse.getRemarks());//备注

        XcCourseTablesDto xcCourseTablesDto = getLearningStatus(userId, courseId);
        xcChooseCourseDto.setLearnStatus(xcCourseTablesDto.getLearnStatus());//学习资格

        return xcChooseCourseDto;
    }




    /**
     * @description 判断学习资格
     * @param userId
     * @param courseId
     * @return XcCourseTablesDto 学习资格状态 [{"code":"702001","desc":"正常学习"},{"code":"702002","desc":"没有选课或选课后没有支付"},{"code":"702003","desc":"已过期需要申请续期或重新支付"}]
     * @author Mr.M
     * @date 2022/10/3 7:37
     */
    @Override
    public XcCourseTablesDto getLearningStatus(String userId, Long courseId) {

        //1.查询我的课程表，如果查不到说明没有选课
        XcCourseTables xcCourseTables = getXcCourseTables(userId, courseId);
        if (xcCourseTables == null){
            XcCourseTablesDto XcCourseTablesDto = new XcCourseTablesDto();
            XcCourseTablesDto.setLearnStatus("702002");//没有选课或选课后没有支付
            return XcCourseTablesDto;
        }

        //2.如果查到了，判断是否过期，如果过期不能继续学习
        boolean isExpires = xcCourseTables.getValidtimeEnd().isBefore(LocalDateTime.now());
        //准备返回的对象
        XcCourseTablesDto xcCourseTablesDto = new XcCourseTablesDto();
        //设置返回参数
        BeanUtils.copyProperties(xcCourseTables,xcCourseTablesDto);
        if (!isExpires){
            //正常学习
            xcCourseTablesDto.setLearnStatus("702001");//正常学习
            return xcCourseTablesDto;
        }else {
            //已过期
            xcCourseTablesDto.setLearnStatus("702003");//已过期
            return xcCourseTablesDto;
        }
    }


    //添加免费课程,免费课程加入选课记录表、我的课程表
    public XcChooseCourse addFreeCoruse(String userId, CoursePublish coursepublish) {

        //1.判断，如果存在免费的选课记录且选课状态为成功，直接返回
        LambdaQueryWrapper<XcChooseCourse> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //查询条件
        lambdaQueryWrapper.eq(XcChooseCourse::getCourseId,coursepublish.getId());//同一课程
        lambdaQueryWrapper.eq(XcChooseCourse::getUserId,userId);//同一用户
        lambdaQueryWrapper.eq(XcChooseCourse::getOrderType,"700001");//免费课程
        lambdaQueryWrapper.eq(XcChooseCourse::getStatus, "701001");//选课成功
        //查询
        List<XcChooseCourse> xcChooseCourses = xcChooseCourseMapper.selectList(lambdaQueryWrapper);
        //判断
        if (xcChooseCourses != null && xcChooseCourses.size()>0) {
            return xcChooseCourses.get(0);
        }

        //2.向选课表插入数据
        XcChooseCourse xcChooseCourse = new XcChooseCourse();
        //设置参数
        xcChooseCourse.setCourseId(coursepublish.getId());//课程id
        xcChooseCourse.setCourseName(coursepublish.getName());//课程名称
        xcChooseCourse.setUserId(userId);//用户id
        xcChooseCourse.setCompanyId(coursepublish.getCompanyId());//机构id
        xcChooseCourse.setOrderType("700001");//选课类型
        xcChooseCourse.setCreateDate(LocalDateTime.now());//添加时间
        xcChooseCourse.setCoursePrice(coursepublish.getPrice());//课程价格
        xcChooseCourse.setValidDays(365);//课程有效期
        xcChooseCourse.setStatus("701001");//选课状态
        xcChooseCourse.setValidtimeStart(LocalDateTime.now());//开始服务时间
        xcChooseCourse.setValidtimeEnd(LocalDateTime.now().plusDays(365));//结束服务时间
        xcChooseCourse.setRemarks(coursepublish.getRemark());//备注
        //插入
        int i = xcChooseCourseMapper.insert(xcChooseCourse);
        //插入失败
        if (i <= 0){
            XueChengPlusException.cast("添加选课失败！");
        }

        //返回
        return xcChooseCourse;
    }


    //添加收费课程
    public XcChooseCourse addChargeCoruse(String userId,CoursePublish coursepublish){

        //1.判断，如果存在收费的选课记录且选课状态为待支付，直接返回
        LambdaQueryWrapper<XcChooseCourse> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //查询条件
        lambdaQueryWrapper.eq(XcChooseCourse::getCourseId,coursepublish.getId());//同一课程
        lambdaQueryWrapper.eq(XcChooseCourse::getUserId,userId);//同一用户
        lambdaQueryWrapper.eq(XcChooseCourse::getOrderType,"700002");//收费课程
        lambdaQueryWrapper.eq(XcChooseCourse::getStatus, "701002");//待支付
        //查询
        List<XcChooseCourse> xcChooseCourses = xcChooseCourseMapper.selectList(lambdaQueryWrapper);
        //判断
        if (xcChooseCourses != null && xcChooseCourses.size()>0) {
            return xcChooseCourses.get(0);
        }

        //2.向选课表插入数据
        XcChooseCourse xcChooseCourse = new XcChooseCourse();
        //设置参数
        xcChooseCourse.setCourseId(coursepublish.getId());//课程id
        xcChooseCourse.setCourseName(coursepublish.getName());//课程名称
        xcChooseCourse.setUserId(userId);//用户id
        xcChooseCourse.setCompanyId(coursepublish.getCompanyId());//机构id
        xcChooseCourse.setOrderType("700002");//选课类型
        xcChooseCourse.setCreateDate(LocalDateTime.now());//添加时间
        xcChooseCourse.setCoursePrice(coursepublish.getPrice());//课程价格
        xcChooseCourse.setValidDays(365);//课程有效期
        xcChooseCourse.setStatus("701002");//选课状态
        xcChooseCourse.setValidtimeStart(LocalDateTime.now());//开始服务时间
        xcChooseCourse.setValidtimeEnd(LocalDateTime.now().plusDays(365));//结束服务时间
        xcChooseCourse.setRemarks(coursepublish.getRemark());//备注
        //插入
        int i = xcChooseCourseMapper.insert(xcChooseCourse);
        //插入失败
        if (i <= 0){
            XueChengPlusException.cast("添加选课失败！");
        }

        //返回
        return xcChooseCourse;
    }


    //添加到我的课程表
    public XcCourseTables addCourseTabls(XcChooseCourse xcChooseCourse){
        //1.选课成功了才向我的课程添加
        String status = xcChooseCourse.getStatus();
        if (!"701001".equals(status)){
            XueChengPlusException.cast("选课未成功，无法添加到课程表");
        }

        //2.我的课程已经有了不添加
        XcCourseTables xcCourseTables = getXcCourseTables(xcChooseCourse.getUserId(), xcChooseCourse.getCourseId());
        if(xcCourseTables!=null){
            return xcCourseTables;
        }

        //3.添加到我的课程表
        XcCourseTables xcCourseTablesNew = new XcCourseTables();
        //设置参数
        xcCourseTablesNew.setChooseCourseId(xcChooseCourse.getId());//选课id
        xcCourseTablesNew.setUserId(xcChooseCourse.getUserId());//用户id
        xcCourseTablesNew.setCourseId(xcChooseCourse.getCourseId());//课程id
        xcCourseTablesNew.setCompanyId(xcChooseCourse.getCompanyId());//机构id
        xcCourseTablesNew.setCourseName(xcChooseCourse.getCourseName());//课程名称
        xcCourseTablesNew.setCreateDate(LocalDateTime.now());//添加时间
        xcCourseTablesNew.setValidtimeStart(xcChooseCourse.getValidtimeStart());//开始服务时间
        xcCourseTablesNew.setValidtimeEnd(xcChooseCourse.getValidtimeEnd());//结束服务时间
        xcCourseTablesNew.setCourseType(xcChooseCourse.getOrderType());//选课类型
        //添加
        xcCourseTablesMapper.insert(xcCourseTablesNew);

        //返回
        return xcCourseTablesNew;
    }


    //根据用户id和课程id查询我的课程表
    public XcCourseTables getXcCourseTables(String userId,Long courseId){
        XcCourseTables xcCourseTables = xcCourseTablesMapper.selectOne(new LambdaQueryWrapper<XcCourseTables>().eq(XcCourseTables::getUserId, userId).eq(XcCourseTables::getCourseId, courseId));
        return xcCourseTables;
    }



    @Transactional
    @Override
    public boolean saveChooseCourseSuccess(String chooseCourseId) {

        //根据choosecourseId查询选课记录
        XcChooseCourse xcChooseCourse = xcChooseCourseMapper.selectById(chooseCourseId);
        if(xcChooseCourse == null){
            log.debug("收到支付结果通知没有查询到关联的选课记录,choosecourseId:{}",chooseCourseId);
            return false;
        }
        String status = xcChooseCourse.getStatus();
        if("701001".equals(status)){
            //添加到课程表
            addCourseTabls(xcChooseCourse);
            return true;
        }
        //待支付状态才处理
        if ("701002".equals(status)) {
            //更新为选课成功
            xcChooseCourse.setStatus("701001");
            int update = xcChooseCourseMapper.updateById(xcChooseCourse);
            if(update>0){
                log.debug("收到支付结果通知处理成功,选课记录:{}",xcChooseCourse);
                //添加到课程表
                addCourseTabls(xcChooseCourse);
                return true;
            }else{
                log.debug("收到支付结果通知处理失败,选课记录:{}",xcChooseCourse);
                return false;
            }
        }

        return false;
    }



    /**
     * @description 我的课程表
     * @param params
     * @return com.xuecheng.base.model.PageResult<com.xuecheng.learning.model.po.XcCourseTables>
     * @author Mr.M
     * @date 2022/10/27 9:24
     */
    @Override
    public PageResult<XcCourseTables> mycoursetables( MyCourseTableParams params){
        //页码
        long pageNo = params.getPage();
        //每页记录数
        long pageSize = params.getSize();
        //分页条件
        Page<XcCourseTables> page = new Page<>(pageNo, pageSize);
        //根据用户id查询
        String userId = params.getUserId();
        LambdaQueryWrapper<XcCourseTables> lambdaQueryWrapper = new LambdaQueryWrapper<XcCourseTables>().eq(XcCourseTables::getUserId, userId);

        //分页查询
        Page<XcCourseTables> pageResult = courseTablesMapper.selectPage(page, lambdaQueryWrapper);
        List<XcCourseTables> records = pageResult.getRecords();
        //记录总数
        long total = pageResult.getTotal();
        PageResult<XcCourseTables> courseTablesResult = new PageResult<>(records, total, pageNo, pageSize);
        return courseTablesResult;

    }


}
